interface StorageState {
	storage: globalThis.Storage
	setItem(name: string, value: string | object): void
}

// 封装存储类
class Storage implements StorageState {
	storage: globalThis.Storage
	constructor(storage: globalThis.Storage) {
		this.storage = storage
	}
	setItem(name: string, value: string | object) {
		// 检测是不是json数据
		if (typeof value === 'object' || typeof value === 'function') {
			// 转化字符串
			value = JSON.stringify(value)
		}
		// 存储本地
		this.storage.setItem(name, value)
	}
	getItem(name: string) {
		const value = this.storage.getItem(name);
		if(!value) return null;
		// 尝试执行代码
		try {
			return JSON.parse(value)
		} catch {
			return value
		}
	}
	removeItem(name: string) {
		this.storage.removeItem(name)
	}
	clear() {
		this.storage.clear()
	 }
}
export const l = new Storage(localStorage)
export const s = new Storage(sessionStorage)

l.setItem('arr', [1, 2, 3, 4, 5])
l.setItem('str', '123456789')
l.setItem('oo', 'q;wldqmwdlqmwdqp;w')

const s1 = l.getItem('arr')   // => [1,2,3,4,5]
const s2 = l.getItem('str')   // => '123456789'
const s4 = l.getItem('oo')
console.log(s1, s2, s4);

s.setItem('obj', { name: '张三', age: 18 })
const s3 = s.getItem('obj')   // => { name: '张三', age: 18 }
console.log(s3)

// 需要
// 1. 将数据  arr  [1,2,3,4]  存入本地存储
// localStorage.setItem('arr', JSON.stringify([1, 2, 3, 4]))

// 2. 获取 arr
// const arr = JSON.parse(localStorage.getItem('arr') || '[]')


// localStorage.removeItem('arr')
// localStorage.clear()
// localStorage.length


// 1. 狗急跳墙
// 2. 东倒西歪
// 3. 害群之马